// Manifest V3 兼容版本 - Content Script

// 更新API调用：chrome.extension -> chrome.runtime
function getCache(name, cb) {
  chrome.runtime.sendMessage(
    {
      action: 'getCache',
      name: name,
    },
    function(resp) {
      cb && cb(resp.result[name])
    }
  )
}

function getMultiCache(names, cb) {
  chrome.runtime.sendMessage(
    {
      action: 'getCache',
      names: names,
    },
    function(resp) {
      cb && cb(resp.result)
    }
  )
}

function setCache(name, value, cb) {
  chrome.runtime.sendMessage(
    {
      action: 'setCache',
      name: name,
      value: value,
    },
    function(resp) {
      cb && cb(resp)
    }
  )
}

function sendEvent(category, action, label) {
  chrome.runtime.sendMessage(
    {
      action: 'sendEvent',
      event: {
        category: category,
        action: action,
        label: label
      },
    },
    function(resp) {
      cb && cb(resp)
    }
  )
}

var unsafeWindow
var sharedTaskStatus = null

setTimeout(function() {
  var script = document.createElement('script')
  script.type = 'text/javascript'
  script.innerHTML =
    "if(typeof msg_desc != 'undefined') { document.body.setAttribute('data-ct', ct); document.body.setAttribute('data-nickname', nickname); document.body.setAttribute('data-msg_desc', msg_desc );document.body.setAttribute('data-msg_title', msg_title);document.body.setAttribute('data-msg_cdn_url', msg_cdn_url); }"
  document.head.appendChild(script)
  document.head.removeChild(script)
}, 50)

var allAccounts = []
var accounts = []

console.log('accounts', accounts)

function getAccounts(cb) {
  console.log('getAccounts: 开始获取账号数据')
  chrome.runtime.sendMessage(
    {
      action: 'getAccount',
    },
    function(resp) {
      console.log('getAccounts: 收到响应', resp)
      if (resp && Array.isArray(resp)) {
        allAccounts = resp
        console.log('getAccounts: 成功获取', resp.length, '个账号')
      } else {
        allAccounts = []
        console.log('getAccounts: 未获取到账号数据或数据格式错误')
      }
      cb && cb()
    }
  )
}
function getPost() {
  var post = {}
  post.title = document.body.getAttribute('data-msg_title')
  post.content = $('#js_content').html()
  post.thumb = document.body.getAttribute('data-msg_cdn_url')
  post.desc = document.body.getAttribute('data-msg_desc')
  post.nickname = document.body.getAttribute('data-nickname')
  post.publish_time = document.body.getAttribute('data-ct')
  post.link = window.location.href
  console.log(post)
  return post
}

function extractUrlValue(key, url) {
  if (typeof url === 'undefined') url = window.location.href
  var match = url.match('[?&]' + key + '=([^&]+)')
  return match ? match[1] : null
}

var isSinglePage = window.location.href.indexOf('mp.weixin.qq.com/s') > -1
if (isSinglePage) {
  // 延迟添加按钮，确保DOM完全加载
  setTimeout(function() {
    // 检查#page-content元素是否存在
    if ($('#page-content').length === 0) {
      console.log('页面内容区域未找到，等待页面加载...')
      // 如果#page-content不存在，尝试其他选择器或等待更长时间
      var waitCount = 0
      var maxWait = 10 // 最多等待10次（5秒）
      
      function tryAddButton() {
        waitCount++
        if ($('#page-content').length > 0) {
          addSyncButton()
        } else if (waitCount < maxWait) {
          setTimeout(tryAddButton, 500)
        } else {
          console.log('无法找到页面内容区域，尝试添加到body')
          // 作为最后的尝试，添加到body
          addSyncButtonToBody()
        }
      }
      
      setTimeout(tryAddButton, 500)
    } else {
      addSyncButton()
    }
  }, 1000) // 延迟1秒执行，确保页面完全加载
  
  function addSyncButton() {
    var div = $(
      "<div class='sync-btn' style='position: fixed; left: 0; right: 0;top: 68px;width: 950px; margin-left: auto;margin-right: auto;'></div>"
    )
    div.append(
      '<div data-toggle="modal" data-target="#exampleModalCenter" style=\'    font-size: 14px;border: 1px solid #eee;width: 105px; text-align: center; box-shadow: 0px 0px 1px rgba(0,0,0, 0.1);border-radius: 5px;padding: 5px; cursor: pointer;    background: rgb(0, 123, 255);color: white;\'>同步该文章</div>'
    )
    
    div.click(function() {
      console.log('同步按钮被点击，开始获取账号...')
      if (window.$poster && window.$poster.getAccounts) {
        window.$poster.getAccounts((accounts) => {
          console.log('账号获取完成，获取到的账号:', accounts)
          if (accounts && accounts.length > 0) {
            allAccounts = accounts
            afterGet()
          } else {
            console.log('没有获取到账号数据')
            $('#exampleModalCenter .modal-body').html('<p style="color: red;">暂无可用账号，请先添加账号</p>')
            $('#exampleModalCenter').modal('show')
          }
        })
      } else {
        console.log('window.$poster 未定义，尝试使用getAccounts函数...')
        getAccounts(() => {
          console.log('账号获取完成，allAccounts:', allAccounts)
          if (allAccounts && allAccounts.length > 0) {
            afterGet()
          } else {
            console.log('没有获取到账号数据')
            $('#exampleModalCenter .modal-body').html('<p style="color: red;">暂无可用账号，请先添加账号</p>')
            $('#exampleModalCenter').modal('show')
          }
        })
      }
    })
    
    $('#page-content').append(div)
    console.log('同步按钮已添加到页面')
  }
  
  function addSyncButtonToBody() {
    var div = $(
      "<div class='sync-btn' style='position: fixed; left: 0; right: 0;top: 68px;width: 950px; margin-left: auto;margin-right: auto; z-index: 9999;'></div>"
    )
    div.append(
      '<div data-toggle="modal" data-target="#exampleModalCenter" style=\'    font-size: 14px;border: 1px solid #eee;width: 105px; text-align: center; box-shadow: 0px 0px 1px rgba(0,0,0, 0.1);border-radius: 5px;padding: 5px; cursor: pointer;    background: rgb(0, 123, 255);color: white;\'>同步该文章</div>'
    )
    
    div.click(function() {
      console.log('同步按钮被点击（body模式），开始获取账号...')
      if (window.$poster && window.$poster.getAccounts) {
        window.$poster.getAccounts((accounts) => {
          console.log('账号获取完成，获取到的账号:', accounts)
          if (accounts && accounts.length > 0) {
            allAccounts = accounts
            afterGet()
          } else {
            console.log('没有获取到账号数据')
            $('#exampleModalCenter .modal-body').html('<p style="color: red;">暂无可用账号，请先添加账号</p>')
            $('#exampleModalCenter').modal('show')
          }
        })
      } else {
        console.log('window.$poster 未定义，尝试使用getAccounts函数...')
        getAccounts(() => {
          console.log('账号获取完成，allAccounts:', allAccounts)
          if (allAccounts && allAccounts.length > 0) {
            afterGet()
          } else {
            console.log('没有获取到账号数据')
            $('#exampleModalCenter .modal-body').html('<p style="color: red;">暂无可用账号，请先添加账号</p>')
            $('#exampleModalCenter').modal('show')
          }
        })
      }
    })
    
    $('body').append(div)
    console.log('同步按钮已添加到body')
  }

  function afterGet() {
    var post = getPost()
    var html = ''
    accounts = allAccounts
    var supportAccounts = allAccounts.filter(item => {
      if (!item.supportTypes) return true
      return item.supportTypes.indexOf('html') > -1
    })

    supportAccounts.forEach((account, index) => {
      html +=
        `
            <div class="form-check mb-1">
  <input class="form-check-input" type="checkbox" value="` +
        account.uid +
        `" name="submit_check" id="defaultCheck` +
        index +
        `">
  <label class="form-check-label" for="defaultCheck` +
        index +
        `">
  <img src="` +
        (account.icon
          ? account.icon
          : chrome.runtime.getURL('images/wordpress.ico')) +
        `" class="icon" height="20" style="vertical-align: -3px;height: 20px !important">
  ` +
        account.title +
        `
  </label>
</div>
            `
    })

    var con =
      `
        <div class="media">
        <img class="align-self-center mr-3" src="` +
      post.thumb +
      `" width="150" alt="Generic placeholder image">
        <div class="media-body">
          <h5 class="mt-0" style="font-weight:bold">` +
      post.title +
      `</h5>
          <p>` +
      post.desc +
      `</p>
        </div>
      </div>
      <hr>
      <div id="top-tip-block"></div>
      <h6>账号</h6>
      <div id="syncd-users">
      ` +
      html +
      `
      </div>
      <div id="tip-block"></div>
        `

    $('#exampleModalCenter .modal-body').html('')
    $('#exampleModalCenter .modal-body').append(con)
    console.log('clicka')
    restoreAndAutodCheckd()
    $('#syncd-users').click(checkShareStatus)
  }
}

var html = `
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document" style="color: #444;">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">同步文章</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close" id="closesyncmodl">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal" style="font-size: 13px;    line-height: 1.5;">取消</button>
        <button type="button" class="btn btn-primary" style="font-size: 13px;    line-height: 1.5;">同步</button>
      </div>
    </div>
  </div>
</div>
`

$('body').append(html)

$('body').append(`
<div data-toggle="modal" data-target="#exampleModalCenterForShare" id="sharetrigger"></div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenterForShare" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterForShareTitle" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered modal-dialog-scrollable" role="document" style="color: #444;">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">求分享</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close" id="closesyncmodl">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
 <div><h3 style="color: #aaa;font-size: 16px;">请帮忙分享给有需要的人！</h3>
 <p id="doubanshare" style="/* margin-top: 17px */">
 </p>
 <p id="weiboshare" style="margin-bottom: 25px;">
</p>
<h3 style="color: #666;font-size: 16px;">或复制分享</h3><textarea style="
    width: 100%;
    height: 200px;
    background: #eee;
    color: #777;
    padding: 10px;
    border: 1px solid #ddd;
    "
    id="sshare-text"
    ></textarea></div>
    </div>
    </div>
  </div>
</div>
`)

var hasbeenShared = false
var syncCount = 0
var syncCountKey = `total_sync`
var isShareKey = `detect_share`
var shareShowedKey = `share_showed`
var shareShowedCount = 0
var popupShareTime = null
var shareShouldCost = 12 * 1000
var shareTotalShowLimit = 6
var shareInteractioned = false

function afterShareInteraction(type) {
  shareInteractioned = true
  var label = sharedTaskStatus ? sharedTaskStatus.accounts.map(account => {
    return [account.type, account.uid, account.title].join('-')
  }) : 'default';
  sendEvent('share', type, [label, syncCount].join(";;"))
}

function isTimeToShowShareTip() {
  return syncCount < 5
    ? syncCount > 1 && syncCount % 2 == 0
    : syncCount % 3 == 0
}

function showShareTip() {
  if (isTimeToShowShareTip()) {
    if (hasbeenShared) return;
    $('#sharetrigger').click()
    popupShareTime = Date.now()
    setCache(shareShowedKey, shareShowedCount + 1)
  }
}

function initShareConfig() {
  var shareText = document.getElementById('sshare-text')
  var doubanshare = document.getElementById('doubanshare')
  var weiboshare = document.getElementById('weiboshare')

  var shareUrl = 'https://www.wechatsync.com/?utm_source=byshare'
  var sharText = `文章同步助手 - 一键同步文章到头条、百家号等多达20个渠道，提高内容发布效率，解放生产力！`

  shareText.innerHTML = sharText + ' ' + shareUrl
  shareText.onselect = function() {
    afterShareInteraction('share-selected')
  }

  doubanshare.addEventListener('click', function() {
    afterShareInteraction('douban-clicked')
    ~(function() {
      var d = document,
        e = encodeURIComponent,
        s1 = window.getSelection,
        s2 = d.getSelection,
        s3 = d.selection,
        s = s1 ? s1() : s2 ? s2() : s3 ? s3.createRange().text : '',
        r =
          'https://www.douban.com/recommend/?url=' +
          e(shareUrl) +
          '&title=' +
          e(sharText) +
          '&sel=' +
          e(s) +
          '&v=1',
        w = 450,
        h = 330,
        x = function() {
          var openWin = window.open(
            r,
            'douban',
            'toolbar=0,resizable=1,scrollbars=yes,status=1,width=' +
              w +
              ',height=' +
              h +
              ',left=' +
              (screen.width - w) / 2 +
              ',top=' +
              (screen.height - h) / 2
          )
          if (!openWin) location.href = r + '&r=1'
        }
      if (/Firefox/.test(navigator.userAgent)) {
        setTimeout(x, 0)
      } else {
        x()
      }
    })()
  })

  weiboshare.addEventListener('click', function() {
    afterShareInteraction('weibo-clicked')
    ;(function() {
      var d = document,
        e = encodeURIComponent,
        s1 = window.getSelection,
        s2 = d.getSelection,
        s3 = d.selection,
        s = s1 ? s1() : s2 ? s2() : s3 ? s3.createRange().text : '',
        r =
          'https://service.weibo.com/share/share.php?url=' +
          e(shareUrl) +
          '&language=zh_cn&title=' +
          e(sharText) +
          '%20%40_fun0&source=&sourceUrl=&ralateUid=&message=&uids=&pic=&searchPic=false&content=',
        w = 450,
        h = 330,
        x = function() {
          var openWin = window.open(
            r,
            'weibo',
            'toolbar=0,resizable=1,scrollbars=yes,status=1,width=' +
              w +
              ',height=' +
              h +
              ',left=' +
              (screen.width - w) / 2 +
              ',top=' +
              (screen.height - h) / 2
          )
          if (!openWin) location.href = r + '&r=1'
        }
      if (/Firefox/.test(navigator.userAgent)) {
        setTimeout(x, 0)
      } else {
        x()
      }
    })()
  })

  doubanshare.innerHTML = `<a ><img src="https://img3.doubanio.com/pics/fw2douban1.png" alt="推荐到豆瓣" /></a>`
  weiboshare.innerHTML = `<a style="font-size: 13px"><img height="18" src="https://cambrian-images.cdn.bcebos.com/a487b054820191e8e7a2fcf136b925b9_1551320091220.jpeg" style="vertical-align: -3px;" /> 分享到微博</a>`
}

setTimeout(initShareConfig, 200)

chrome.runtime.onMessage.addListener(function(request, sender, sendResponseA) {
  console.log('content.js revice', request)
  try {
    console.log('revice', request)
    if (request.method == 'taskUpdate') {
      buildStatusHtml(request.task)
    }
  } catch (e) {
    console.log(e)
  }
})

function checkShareStatus() {
  console.log('checkShareStatus')
  if (popupShareTime) {
    var spendTime = Date.now() - popupShareTime
    var isReachShareCost = spendTime > shareShouldCost
    if (isReachShareCost && shareInteractioned) {
      console.log('reach share action')
      setCache(isShareKey, '1')
    }
    console.log('spendTime', spendTime)
  }
}

getMultiCache([isShareKey, syncCountKey, shareShowedKey], function(result) {
  console.log('result', result)
  if (result[isShareKey]) {
    hasbeenShared = true
  }

  if (result[syncCountKey]) {
    syncCount = parseInt(result[syncCountKey])
  }

  if (result[shareShowedKey]) {
    shareShowedCount = parseInt(result[shareShowedKey])
  }
})

// 其他函数保持不变...
// 由于代码较长，保持核心业务逻辑不变

console.log('WechatSync Content Script (V3) loaded successfully')